package com.wk.controller;

import com.wk.entity.ManagerInfo;
import com.wk.exception.ForbiddenUserException;
import com.wk.service.impl.ManagerInfoServiceImpl;
import com.wk.shiro.IncorrectCaptchaException;
import com.wk.shiro.ShiroKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
@Slf4j
public class LoginController {

    @Autowired
    private ManagerInfoServiceImpl managerInfoService;

    //登录页(shiro配置需要两个/login 接口,一个是get用来获取登陆页面,一个用post用于登录)
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login()
    {
        if(ShiroKit.isAuthenticated())
        {
            return "redirect:/";
        }
        return "login";
    }

    // 登录提交地址和shiroConfig配置的保持一致
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(HttpServletRequest request, Map<String, Object> map)
    {
        log.info("登录方法start.......");
        Object exception = request.getAttribute("shiroLoginFailure");
        String msg;
        if (exception != null)
        {
            if (UnknownAccountException.class.isInstance(exception))
            {
                msg = "用户名不正确，请重新输入";
            }else if(IncorrectCredentialsException.class.isInstance(exception)){
                msg = "密码错误，请重新输入";
            }else if(IncorrectCaptchaException.class.isInstance(exception)){
                msg = "验证码错误";
            }else if(ForbiddenUserException.class.isInstance(exception)){
                msg = "该用户已被禁用，如有疑问请联系系统管理员。";
            }else{
                msg = "发生未知错误，请联系管理员。";
            }
            map.put("username", request.getParameter("username"));
            map.put("password", request.getParameter("password"));
            map.put("msg",msg);
            return "login";
        }

        //如果已经登录，直接跳转主页面
        return "index";
    }

    /**
     * 主页
     * @param session
     * @param model
     * @return
     */
    @RequestMapping({"/", "/index"})
    public String index(HttpSession session, Model model)
    {
        // log.info("访问首页start...");
        // 做一些其他事情，比如把项目的数量放到session中
        if (ShiroKit.hasRole("admin") && session.getAttribute("projectNum") == null)
        {
            session.setAttribute("projectNum",2);
        }
        return "index";
    }
}
